<template>
	<view class="container">
		<view class="search-bar">
			<uni-search-bar v-model="searchKeyword" radius="20" placeholder="输入名称或描述" @confirm="handleSearch"
				@clear="handleSearchClear" cancelButton="none" style="flex: 1;" />
			<button class="add-btn" @click="addThing">新增商品</button>
		</view>

		<view class="thing-list" v-if="things && things.length > 0">
			<view v-for="(item,index) in things" :key="item._id" class="thing-item">
				<image v-for="(img,index1) in item.imageUrl" :src="img" mode="heightFix" class="thumb"
					@error="handleImageErr(item,index1)" :key="index1">
				</image>
				<view class="info">
					<text>{{ item.name }}</text>
					<text>描述：{{item.desc}}</text>
					<view class="price">
						<text style="color:#333;font-size: 28rpx;font-weight: 400;">单价：</text>
						<text class="tig" style="color: red;font-size: 24rpx;">¥</text>
						<text class="number" style="color: red;font-size: 32rpx;font-weight: 600;">{{ item.price }}</text>
						<text class="unit">元/{{ item.unit }}</text>
					</view>
					<text>规格：{{item.specs}}</text>
					<text>已接龙： {{item.joinNumber}}/{{ item.number }} {{ item.unit }}</text>
					<view class="time">
						<text>开始时间：{{formatTime(item.createTime)}}</text>
						<text
							:style="{color:(Date.now()>item.endTime.getTime()?'#f39c12':'#07c160')}">结束时间：{{formatTime(item.endTime)}}</text>
					</view>
				</view>
				<view class="actions">
					<button :disabled="item.createUser!==userInfo.openid"
						:class="{ 'disabled-btn': item.createUser!==userInfo.openid }" @click="editThing(item)">编辑</button>
					<button :disabled="item.createUser!==userInfo.openid"
						:class="{ 'disabled-btn': item.createUser!==userInfo.openid }"
						@click="deleteThing(item._id,index)">删除</button>
					<button @click="detailThing(item._id)">详情</button>
				</view>
			</view>
		</view>

		<view class="safe-area-box">
			<uni-load-more :status="status" />
		</view>

		<!-- 添加/编辑商品弹窗 -->
		<uni-popup ref="popup" type="dialog">
			<uni-popup-dialog mode="input" title="商品信息" @confirm="handleSubmit" @close="handleCancel">
				<view class="dialog">
					<label>
						<text class="label">名称</text>
						<input v-model="formData.name" placeholder="商品名称" />
					</label>
					<label>
						<text class="label">价格</text>
						<input v-model.number="formData.price" type="number" placeholder="价格" />
					</label>
					<label>
						<text class="label">单位</text>
						<input v-model="formData.unit" placeholder="单位" />
					</label>
					<label>
						<text class="label">数量</text>
						<input v-model.number="formData.number" placeholder="数量" />
					</label>
					<label>
						<text class="label">规格</text>
						<input v-model="formData.specs" placeholder="规格" />
					</label>
					<label>
						<text class="label">描述</text>
						<textarea v-model="formData.desc" placeholder="描述"></textarea>
					</label>
					<label>
						<text class="label image">图片</text>
						<uni-file-picker :value="formData.imageUrl" :limit="3" @select="onSelect"
							@delete="deleteImage"></uni-file-picker>
					</label>
					<label>
						<text class="label time">结束时间</text>
						<uni-datetime-picker v-model="formData.endTime"></uni-datetime-picker>
					</label>
				</view>
			</uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
	import {
		ref,
		onMounted,
		watch,
		onUnmounted
	} from 'vue'
	import {
		formatTime,
		wxLogin
	} from '../../utils/util'
	import {
		onLoad,
		onReachBottom,
		onPullDownRefresh
	} from '@dcloudio/uni-app'

	const db = wx.cloud.database()
	const things = ref([])
	const formData = ref({
		name: '',
		price: 0,
		unit: '',
		number: 0,
		specs: '',
		desc: '',
		image: [],
		endTime: null
	})
	const currentId = ref('')
	const popup = ref(null)
	const searchKeyword = ref('')
	let lastCreateTime = null
	let pageSize = 2
	const status = ref('more')
	let userInfo = null

	onLoad(async () => {
		userInfo = uni.getStorageSync('userInfo')
		if (!userInfo.openid) {
			const res = await wxLogin()
			userInfo = res
		}
	})

	onMounted(() => {
		console.log("userInfo:", userInfo);
		getThings()
	})

	onUnmounted(() => {
		cleanCloudImage()
		console.log("onUn执行了");
	})

	let oldImages = []
	let deleteImages = []
	const cleanCloudImage = () => {
		let fileList = [...deleteImages, ...formData.value.image]
		if (oldImages.length > 0) {
			fileList = fileList.filter(item => !oldImages.includes(item))
		}
		if (fileList.length > 0) {
			wx.cloud.deleteFile({
				fileList: fileList
			})
		}
		formData.value.image = []
		deleteImages = []
		oldImages = []
	}

	async function getThings(page = 0) {
		if (page === 1) {
			lastCreateTime = null
			things.value = []
			status.value = 'more'
		}
		if (status.value === 'no-more') {
			return
		}
		status.value = 'loading'
		const conditions = []
		if (lastCreateTime) {
			conditions.push({
				createTime: db.command.lt(lastCreateTime)
			})
		} else {
			conditions.push({
				createTime: db.command.lt(new Date())
			})
		}
		if (searchKeyword.value) {
			conditions.push(db.command.or([{
				name: db.RegExp({
					regexp: searchKeyword.value.trim()
				})
			}, {
				desc: db.RegExp({
					regexp: searchKeyword.value.trim()
				})
			}]))
		}

		const res = await db.collection('jeilong_things').where(db.command.and(conditions)).field({
				_openid: false
			})
			.orderBy('createTime', 'desc')
			.limit(pageSize)
			.get()
		if (res.data.length === 0) {
			status.value = 'no-more'
		} else {
			if (res.data.length < pageSize) {
				status.value = 'no-more'
			} else {
				status.value = 'more'
				lastCreateTime = res.data[res.data.length - 1].createTime
			}
			things.value.push(...res.data)
		}
		console.log("things列表：", lastCreateTime);
		const res1 = await Promise.all(things.value.map(item => {
			item.imageUrl = [...item.image]
			return db.collection('jeilong_relation').field({
				number: true
			}).where({
				thingId: item._id
			}).get()
		}))

		res1.forEach((item, index) => {
			things.value[index].joinNumber = item.data.reduce((acc, cur) => acc + cur.number, 0)
		})
	}

	const handleImageErr = async (thing, index) => {
		if (thing.image[index]) {
			const res = await wx.cloud.getTempFileURL({
				fileList: [thing.image[index]]
			});
			thing.imageUrl[index] = res.fileList[0].tempFileURL
		} else {
			thing.imageUrl[index] = ''
		}
		console.log('临时图片地址：', thing.imageUrl[index]);
	}

	const handleSearch = () => {
		getThings(1)
	}

	const handleSearchClear = () => {
		getThings(1)
	}

	const addThing = () => {
		currentId.value = ''
		cleanCloudImage()
		formData.value = {
			name: '',
			price: 0,
			unit: '',
			number: 0,
			specs: '',
			desc: '',
			image: [],
			endTime: null
		}
		popup.value.open()
	}

	async function editThing(item) {
		currentId.value = item._id
		cleanCloudImage()
		if (item.image.length > 0) {
			oldImages = item.image
		}
		formData.value = {
			...item
		}
		if (formData.value.image && formData.value.image.length > 0) {
			console.log(formData.value.image);
			const res = await wx.cloud.getTempFileURL({
				fileList: formData.value.image
			});
			formData.value.imageUrl = res.fileList.map(item => {
				const arr = item.fileID.split('/')
				const name = arr[arr.length - 1]
				const extname = name.split('.')[1]
				return {
					name,
					extname,
					url: item.tempFileURL
				}
			})
		}
		popup.value.open()
	}

	async function handleSubmit() {
		if (currentId.value) {
			const {
				_id,
				imageUrl,
				joinNumber,
				...data
			} = formData.value
			data.endTime = new Date(data.endTime)
			// 更新
			await db.collection('jeilong_things').doc(currentId.value).update({
				data
			})
			things.value[things.value.findIndex(item => item._id === currentId.value)] = {
				_id: currentId.value,
				imageUrl,
				joinNumber,
				...data,
			}
		} else {
			// 新增
			await db.collection('jeilong_things').add({
				data: {
					...formData.value,
					createUser: userInfo.openid,
					createTime: db.serverDate(),
					endTime: new Date(formData.value.endTime)
				}
			})
			await getThings(1)
		}
		const fileList = [...new Set([...oldImages, ...deleteImages])].filter(item => !formData.value.image.includes(item))
		formData.value.image = []
		if (fileList.length > 0) {
			wx.cloud.deleteFile({
				fileList: fileList
			})
		}

		uni.showToast({
			title: currentId.value ? '修改成功' : '添加成功'
		})
	}

	async function deleteThing(id, index) {
		const res = await uni.showModal({
			title: '提示',
			content: '你确定要删除 ' + things.value[index].name + ' 吗？'
		})
		if (res.cancel) {
			return
		}
		if (things.value[index].image.length > 0) {
			wx.cloud.deleteFile({
				fileList: things.value[index].image
			})
		}
		await db.collection('jeilong_things').doc(id).remove()
		things.value.splice(index, 1)
		uni.showToast({
			title: '删除成功'
		})
	}

	const onSelect = async (e) => {
		console.log(formData.value.imageUrl);
		const paths = e.tempFiles.filter(item => item.size < 5 * 1024 * 1024)
		if (paths.length !== e.tempFiles.length) {
			uni.showToast({
				title: paths.length ? '部分文件超过5MB限制' : '文件超过5MB限制',
				icon: 'none'
			})
		}
		try {
			for (let path of e.tempFilePaths) {
				const cloudFileName = `images/${Date.now()}-${Math.random().toString(36).slice(2,4)}.jpg`
				const {
					fileID
				} = await wx.cloud.uploadFile({
					filePath: path,
					cloudPath: cloudFileName,
				})
				formData.value.image.push(fileID)
			}
		} catch (err) {
			console.error('上传失败:', err)
		}
	}

	const deleteImage = async (e) => {
		deleteImages.push(formData.value.image[e.index])
		formData.value.image.splice(e.index, 1)
	}

	const detailThing = (id) => {
		uni.navigateTo({
			url: "/pages/detail/detail?id=" + id
		})
	}

	const handleCancel = () => {
		cleanCloudImage()
		popup.value.close()
	}

	onReachBottom(() => {
		if (status.value === 'more') {
			getThings()
			setTimeout(() => {
				console.log('加载更多。。。。。', status.value)
			}, 1000)
		}
	})

	onPullDownRefresh(() => {
		console.log('下拉刷新');
		getThings(1)
		uni.stopPullDownRefresh()
	})
</script>
<style lang="scss" scoped>
	.container {
		padding: 140rpx 20rpx 20rpx;
		background-color: #f8f8f8;
		min-height: 100vh;

		.search-bar {
			display: flex;
			align-items: center;
			padding: 20rpx 30rpx 20rpx 20rpx;
			background-color: #ffffff;
			border-bottom: 1rpx solid #eee;
			box-sizing: border-box;
			width: 100%;
			height: 120rpx;
			position: fixed;
			top: 0;
			left: 0;
			z-index: 5;

			.add-btn {
				width: 30%;
				height: 64rpx;
				line-height: 64rpx;
				font-size: 28rpx;
				background-color: #07c160;
				color: #fff;
				// border-radius: 40rpx;
				// margin-bottom: 30rpx;

				&::after {
					border: none;
				}

				&:active {
					opacity: 0.9;
				}
			}
		}

		.safe-area-box {
			padding: 20rpx 0;
			margin-bottom: env(safe-area-inset-bottom);
		}
	}

	/* 新增商品按钮 */
	// button {
	// 	width: 100%;
	// 	height: 80rpx;
	// 	line-height: 80rpx;
	// 	background-color: #07c160;
	// 	color: white;
	// 	border-radius: 40rpx;
	// 	font-size: 32rpx;
	// 	margin-bottom: 30rpx;

	// 	&::after {
	// 		border: none;
	// 	}

	// 	&:active {
	// 		opacity: 0.9;
	// 	}
	// }

	/* 商品列表 */
	.thing-list {
		display: grid;
		gap: 24rpx;
	}

	.thing-item {
		background-color: #fff;
		border-radius: 16rpx;
		padding: 24rpx;
		box-shadow: 0 4rpx 12rpx rgba(0, 0, 0, 0.08);
		display: flex;
		flex-direction: column;
	}

	/* 商品缩略图 */
	.thumb {
		// width: 300rpx;
		height: 300rpx;
		border-radius: 8rpx;
		margin-bottom: 20rpx;
		background-color: #f8f8f8;
		object-fit: cover;
	}

	/* 商品信息区域 */
	.info {
		display: flex;
		flex-direction: column;
		gap: 12rpx;

		text {
			font-size: 28rpx;
			color: #333;
			line-height: 1.6;

			&:first-child {
				font-size: 32rpx;
				font-weight: bold;
				margin-bottom: 8rpx;
			}
		}

		.price {}

		.time {
			display: flex;
			flex-direction: column;
			margin-top: 16rpx;
			padding-top: 16rpx;
			border-top: 1rpx dashed #eee;

			text {
				font-size: 24rpx;
				color: #f39c12;
				font-weight: 500;
			}
		}
	}

	/* 操作按钮区域 */
	.actions {
		display: flex;
		gap: 20rpx;
		margin-top: 24rpx;

		button {
			flex: 1;
			height: 64rpx;
			line-height: 64rpx;
			font-size: 28rpx;
			background-color: #f1f1f1;
			color: #333;

			&.disabled-btn {
				opacity: 0.6;
			}

			&:first-child {
				background-color: #2979ff;
				color: white;
			}

			&:nth-child(2) {
				background-color: #ff5a5f;
				color: white;
			}

			&:first-child.disabled-btn {
				background-color: #a0c4ff !important; // 比原色浅的蓝色
			}

			&:nth-child(2).disabled-btn {
				background-color: #ffb3b3 !important; // 比原色浅的红色
			}
		}
	}

	/* 弹窗表单样式 */
	.dialog {
		max-height: 70vh;
		overflow-y: auto;
		padding: 20rpx 0;

		label {
			width: 100%;
			display: flex;
			flex-direction: row;
			align-items: center;
			margin-bottom: 20rpx;
			font-size: 28rpx;
			color: #333;

			.label {
				min-width: 56rpx; // 固定标签宽度
				text-align: right; // 文字右对齐
				padding-right: 20rpx; // 标签和输入框间距
			}

			input,
			textarea {
				width: 100%;
				height: 80rpx;
				padding: 0 20rpx;
				margin-top: 12rpx;
				background-color: #f8f8f8;
				border-radius: 8rpx;
				font-size: 28rpx;
			}

			textarea {
				height: 120rpx;
				padding: 20rpx;
			}
		}
	}

	/* 文件选择器样式覆盖 */
	:deep(.uni-file-picker__header) {
		padding: 0 !important;
	}

	:deep(.uni-file-picker__container) {
		margin-top: 12rpx !important;
	}

	/* 时间选择器样式 */
	:deep(.uni-date-editor) {
		width: 100%;
		margin-top: 12rpx;
	}
</style>